package com.dh.blog.handler.xml;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.Queue;

import com.dh.blog.utils.PatternInjectUtils;

/**
 * xml(html)目录
 * @author David
 *
 */
public class XmlCatalog implements Catalog<XmlNode>,Serializable{
	private static final String ROOT_INDEX = "c";
	private static final String ROOT_TEXT = "目录";
	private static final String XML_ID = "catalog";
	private XmlTemplates template = XmlTemplates.DIV_UL_CATALOG;
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -3609590419119777372L;
	private XmlNode xNode = null;
	public XmlCatalog(){
		this.xNode = new XmlNode();
		xNode.addAttr(XmlNode.INDEX_KEY, ROOT_INDEX);
//		xNode.setText(ROOT_TEXT);
	}
	public void addNode(String index,XmlNode... t) {
		XmlNode node = findNode(index);
		if(null != node){
			int le = node.level()+1;
			int st = node.childNum();
			for(int i = 0;i<t.length;i++){
				t[i].setParent(node);
				t[i].addAttr(XmlNode.INDEX_KEY, index+st);//level+offset作为索引
				t[i].setLevel(le);
				t[i].setOffset(st);
				st++;
			}
			node.addChilds(t);
		}
	}
	public void addNode(XmlNode... t) {
		addNode(ROOT_INDEX,t);
	}
	public int removeNode(String index) {
		XmlNode node = findNode(index);
		if(null != node){
			remove0(node);
			return 1;
		}else{
			return 0;
		}
	}

	public int modifyNode(String index, XmlNode t) {
		XmlNode node = findNode(index);
		if(null != node){
			node.update(t);//g更新
			return 1;
		}else{		
			return 0;
		}
	}

	public XmlNode findNode(String index) {
		if(null == index || "".equals(index)){
			throw new NullPointerException("index is empty");
		}
		XmlNode temp = xNode;
		Queue<XmlNode> queue = new LinkedList<XmlNode>();
		while(null!=temp&&!index.equals(temp.getAttr(XmlNode.INDEX_KEY))){
			for(int i = 0;i< temp.childNum();i++){
				queue.add((XmlNode) temp.getChilds()[i]);
			}
			temp = queue.poll();
		}
		return temp;
	}
	/**
	 * 移动 = 删除+增加
	 */
	public int moveNode(String index, int level, int offset) {
		XmlNode node = findNode(index);
		if(null != node){
			remove0(node);
			addNode(""+level+offset, node);
			return 1;
		}else{		
			return 0;
		}
	}
	/**
	 * 实质将root结点序列化，外围包裹起来
	 */
	public String serialize() {
		return PatternInjectUtils.inject(template.getValue(), 
				new String[]{XML_ID,xNode.serialize()});
	}
	private void remove0(XmlNode node){
		XmlNode parent = (XmlNode) node.getParent();
		parent.removeChild(node.offset());
	}
}
